package cool.mtc.minghe.service.service.sys.role.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cool.mtc.core.exception.ServiceException;
import cool.mtc.core.page.PageData;
import cool.mtc.minghe.data.entity.sys.role.RoleDO;
import cool.mtc.minghe.data.entity.sys.role.RolePermissionDO;
import cool.mtc.minghe.data.model.base.Dict;
import cool.mtc.minghe.data.model.sys.role.dto.RoleDTO;
import cool.mtc.minghe.data.model.sys.role.dto.RoleListDTO;
import cool.mtc.minghe.data.model.sys.role.form.RoleForm;
import cool.mtc.minghe.data.model.sys.role.query.RoleQuery;
import cool.mtc.minghe.service.manager.sys.role.RoleManager;
import cool.mtc.minghe.service.mapper.sys.role.RoleMapper;
import cool.mtc.minghe.service.mapper.sys.role.RolePermissionMapper;
import cool.mtc.minghe.service.service.sys.role.RoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 明河
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RoleServiceImpl extends cool.mtc.minghe.service.service.BaseServiceImpl implements RoleService {
    private final RoleMapper roleMapper;
    private final RolePermissionMapper rolePermissionMapper;

    private final RoleManager roleManager;

    @Override
    @Transactional
    public long insert(RoleForm form) {
        RoleDO roleDO = form.transToDO();
        roleDO.setCreator(userId());
        roleDO.setId(null);
        roleMapper.insert(roleDO);
        return roleDO.getId();
    }

    @Override
    @Transactional
    public void update(RoleForm form) {
        RoleDO roleDO = roleMapper.selectById(form.getId());
        if (null == roleDO) {
            throw new ServiceException("当前数据已过期，请刷新后重新！(i18n)");
        }
        form.updateDO(roleDO);
        roleMapper.updateById(roleDO);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        if (null == id) {
            return;
        }
        RoleDO roleDO = roleMapper.selectById(id);
        if (null == roleDO) {
            return;
        }
        this.handleCheckCanDelete(roleDO);
        roleMapper.deleteById(id);
    }

    /**
     * 检查是否可以删除
     */
    private void handleCheckCanDelete(RoleDO roleDO) {
        if (Boolean.TRUE.equals(roleDO.getPreset())) {
            throw new ServiceException("preset.delete.not_allow");
        }
        QueryWrapper<RolePermissionDO> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleDO.getId());
        long usedCount = rolePermissionMapper.selectCount(wrapper);
        if (0 == usedCount) {
            return;
        }
        // TODO 检查是否可以删除（检查是否关联user_org_role）
        throw new ServiceException("todo 当前数据已关联其他数据，无法删除！");
    }

    @Override
    public PageData<RoleListDTO> pageList(RoleQuery query) {
        OrderItem[] items = {
                OrderItem.asc("R.order_index"),
        };
        Page<RoleListDTO> page = roleMapper.pageList(super.pageParam(items), query);
        return PageData.of(page.getRecords(), page.getTotal());
    }

    @Override
    public RoleDTO info(Long id) {
        if (null == id) {
            return null;
        }
        return roleMapper.getById(id);
    }

    @Override
    public List<Dict> listDict() {
        return roleManager.listDict();
    }
}
